package com.kdtech.analyse.news;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 深圳文化服务网
 */
public class SzwenNewsAnalyse implements AnalyseNews {
	private static final String[] regex={
		"http://www.szwen.gov.cn/engine/gettemplate.jsp[?]temp_Id=[0-9]*&guid=[a-z0-9]*",
		"http://szwen.gov.cn/engine/gettemplate.jsp[?]guid=.*&temp_Id=[0-9]*",
		"http://www.szwen.gov.cn/engine/gettemplate.jsp[?]guid=.*&temp_Id=[0-9]*",
		"http://www.szwen.cn/engine/gettemplate.jsp\\?guid=[0-9a-z]+&temp_Id=[0-9]+"
	};	
	
	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}		
		NewsMeta news=new NewsMeta();
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();	
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);				
		news.setUrl(url);	
		
		title =doc.select("b.newstitle").text();
		if(StringUtils.isBlank(title)){
			title =doc.select("div.title").text();
		}
		content=HtmlCleaner.getContentHtml(url,doc.select("td.txt4"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.news_areabox"));
		}
		date=DateUtils.matchDate(doc.select("td[height=30]").text());
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);	
		news.setType(1);	
		return news;
	}	
	public static void main(String[] args) {
		String url="http://www.szwen.cn/engine/gettemplate.jsp?temp_Id=7&guid=4bdbadb24f02b9aa014fd399f2a90389";
		SzwenNewsAnalyse analyse=new SzwenNewsAnalyse();		
		url = UrlArgumentTop.FromatUrl(url);
		System.out.println(UrlArgumentTop.FromatUrl(url));
		System.err.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
